(function(doc, win) {
  var docEl = doc.documentElement,
    isIOS = navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i),
    dpr = isIOS ? Math.min(win.devicePixelRatio, 3) : 1,
    dpr = window.top === window.self ? dpr : 1, //被iframe引用时，禁止缩放
    dpr = 1,
    scale = 1 / dpr,
    resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize';
  docEl.dataset.dpr = dpr;
  var metaEl = doc.createElement('meta');
  metaEl.name = 'viewport';
  metaEl.content = 'initial-scale=' + scale + ',maximum-scale=' + scale + ', minimum-scale=' + scale;
  docEl.firstElementChild.appendChild(metaEl);
  var recalc = function() {
    var width = docEl.clientWidth;
    if (width / dpr > 750) {
      width = 750 * dpr;
    }
    // 乘以100，px : rem = 100 : 1
    docEl.style.fontSize = 100 * (width / 750) + 'px';
  };
  recalc()
  if (!doc.addEventListener) return;
  win.addEventListener(resizeEvt, recalc, false);
})(document, window);

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  return (false);
}

let removeAllClass = (className, removeClass) => {
  //找到所有包含className的结点
  let nodeList = document.querySelectorAll(`.${className}`);
  //删除这些标签对应的class
  Array.prototype.forEach.call(nodeList, (el) => {
    el.classList.remove(removeClass)
  })
}
let addAllClass = (className, addClass) => {
  //找到所有包含className的结点
  let nodeList = document.querySelectorAll(`.${className}`);
  //删除这些标签对应的class
  Array.prototype.forEach.call(nodeList, (el) => {
    el.classList.add(addClass)
  })
}
window.pc = {}
const offerParams = {
  offerToRecieveAudio: true,
  offerToRecieveVideo: true
}
let callFlag = false
let acceptCall = false
let senderName = ''
let pass = {}
let timer = null
let count = 0
let localStream = null
const config = {
  'iceServers': [{
      'urls': ['stun:stun.l.google.com:19302']
    },
    {
      'urls': [baseconfig.iceServer], // 自己搭建服务器地址
      "username": baseconfig.username,
      "credential": baseconfig.credential
    },
  ],
}
let timeString = '正在呼叫'
let startTime = function() {
  const dom = $('.callTime')
  clearInterval(timer)
  timer = setInterval(() => {
    count++;
    dom.html(showNum(parseInt(count / 60 / 60)) + ':' + showNum(parseInt(count / 60) % 60) + ':' + showNum(
      count % 60))
    timeString = showNum(parseInt(count / 60 / 60)) + ':' + showNum(parseInt(count / 60) % 60) + ':' + showNum(
      count % 60)
  }, 1000)
}

function showNum(num) {
  if (num < 10) {
    return '0' + num
  }
  return num
}
let stream = {}

function beginTime(group, idfer) {
  let begin = 0
  let beginr = null

  beginr = setInterval(() => {
    begin++
    // console.log(begin)
    if (begin === 100000) {
      clearInterval(beginr)
      if (idfer === 1 && callFlag) {
        return false
      }
      timeOut(() => {
        if (idfer === 0) {
          // console.log(Object.keys(group))
          Object.keys(group).forEach(key => {
            // console.log(stream[key])
            if (!stream[key]) {
              $('.v-status_' + key).removeClass('hidden')
              $('.v-status_' + key).text('无响应')
              $('.loader_' + key).addClass('hidden')
              $('.v-modal_' + key + ' .cuIcon-phone').removeClass('hidden')
            }
          })
        }
      }, idfer)
    }
  }, 1000)
}
const isJSON = function(data) {
  if (typeof(data) === 'object') {
    return data
  } else {
    if (data) {
      return JSON.parse(data)
    } else {
      return false
    }
  }
}
let allMember = JSON.parse(decodeURIComponent(getQueryVariable('group')))
const updateGroupsInfo = function(memeber) { // 更新音频通话人信息
  if (memeber) allMember = {
    ...memeber,
    ...allMember
  }
  let html = ``
  let me = ''
  if (Object.keys(allMember).length > 4) {
    $('#videos').addClass('col-3')
    $('#videos').removeClass('col-2')
  } else {
    $('#videos').removeClass('col-3')
    $('#videos').addClass('col-2')
  }
  if (memeber) {
    Object.keys(memeber).forEach(key => {
      const url = baseconfig.avatarUrl  + '/' + key + '.jpg'
      const avatar = baseconfig.avatarUrl  + '/' + key + '.jpg'
      html += `<div class="v-item">
                   <div class="v-thumb">
                   <div class="v-thumb-bg" style="background:rgba(255,255,255,255.1) url(${url}) no-repeat center center;background-size: cover">  </div>
                    <img src="${avatar}" alt="">
                    <span>${memeber[key]}</span>
                    </div>
                   <audio id="my_video_${key}" autoplay></audio>
                   <div class="v-modal v-modal_${key}">
                    <span class="text-gray cuIcon-phone text-xxl hidden" data-key="${key}"></span>
                   </div>
                   <div class="volume volume_${key}"></div>
                   <div class="loader-71 loader_${key}"></div>
                   <span class="v-voice text-gray cuIcon-voicefill v-voice_${key}"></span>
                   <button class="v-status v-status_${key} hidden cu-btn sx absolute bg-red position-left-half postion-center-x position-bottom-sm">已拒绝</button>
               </div>`
    })
    $('#videos').prepend(html)
    $("#videos").trigger("create") /// 重置css样式
  } else {
    Object.keys(allMember).forEach((key) => {
      const url = baseconfig.avatarUrl +  '/' + key + '.jpg'
      const avatar = baseconfig.avatarUrl  + '/' + key + '.jpg'
      if (key == getQueryVariable('id')) {
        me = `<div class="v-item">
                     <div class="v-thumb" >
                        <div class="v-thumb-bg" style="background:rgba(255,255,255,255.1) url(${url}) no-repeat center center;background-size: cover">  </div>
                        <img class="solids shadow" src="${avatar}" alt="">
                        <span>${allMember[key]}</span>
                        <span class="my-sign text-brown cuIcon-favorfill"></span>
                      </div>
                      <div class="volume volume_${key}"></div>
                      <audio id="my_video_${key}" autoplay muted></audio>
                     <span class="v-voice text-green cuIcon-voicefill v-voice_${key}"></span>
                 </div>`
      } else {
        html += `<div class="v-item">
                      <div class="v-thumb">
                      <div class="v-thumb-bg" style="background:rgba(255,255,255,0.1) url(${url}) no-repeat center center;background-size: cover">  </div>
                       <img class="solids shadow" src="${avatar}" alt="">
                       <span>${allMember[key]}</span>
                      </div>
                      <audio id="my_video_${key}" autoplay></audio>
                      <div class="v-modal v-modal_${key}">
                        <span class="text-gray cuIcon-phone text-xxl hidden" data-key="${key}"></span>
                      </div>
                      <div class="volume volume_${key}"></div>
                      <div class="loader-71 loader_${key}"></div>
                      <span class="v-voice text-gray cuIcon-voicefill v-voice_${key}"></span>
                      <button class="v-status v-status_${key} hidden cu-btn sx absolute bg-red position-left-half postion-center-x position-bottom-sm">已拒绝</button>
                  </div>`
      }
    })
    html = html + me
    $('#videos').html(html)
    $("#videos").trigger("create") /// 重置css样式

  }
  if (Object.keys(allMember).length > 4) {
    $('.v-thumb img').css({
      'width': '40px',
      'height': '40px'
    })
  } else {
    $('.v-thumb img').css({
      'width': '80px',
      'height': '80px'
    })
  }
  $('.v-modal .cuIcon-phone').off('click')
  $('.v-modal .cuIcon-phone').on('click', function() {
    // console.log('???????????????点击事件触发几次????????????????????')
    const key = $(this).attr('data-key')
    $(this).addClass('hidden')
    $('.v-status_' + key).addClass('hidden')
    $('.loader_' + key).removeClass('hidden')
    postMsg({
      groupRecall: 'groupRecall',
      message: allMember,
      uid: key
    }, '*');
  })
}
const updateGroupsInfoVideo = function(memeber) { // 更新视频通话人信息
  if (memeber) allMember = {
    ...memeber,
    ...allMember
  }
  let html = ``
  let me = ''
  if (Object.keys(allMember).length > 4) {
    $('#videos').addClass('col-3')
    $('#videos').removeClass('col-2')
  } else {
    $('#videos').removeClass('col-3')
    $('#videos').addClass('col-2')
  }
  if (memeber) {
    Object.keys(memeber).forEach(key => {
      const url = baseconfig.avatarUrl +  '/' + key + '.jpg'
      const avatar = baseconfig.avatarUrl  + '/' + key + '.jpg'
      html += `<div class="v-item">
                     <div class="v-thumb v-thumb_${key}">
                     <div class="v-thumb-bg" style="background:rgba(255,255,255,255.1) url(${url}) no-repeat center center;background-size: cover">  </div>
                       <img src="${avatar}" alt="">
                       <span>${memeber[key]}</span>
                       <video x5-playsinline playsinline webkit-playsinline preload id="my_video_${key}" autoplay poster="${url}"></video>
                      </div>
                     <div class="v-modal v-modal_${key}">
                      <span class="text-gray cuIcon-phone text-xxl hidden" data-key="${key}"></span>
                     </div>
                     <div class="volume volume_${key}"></div>
                     <div class="loader-71 loader_${key}"></div>
                     <span class="v-voice text-gray cuIcon-voicefill v-voice_${key}"></span>
                     <span class="v-record text-gray cuIcon-recordfill v-record_${key}"></span>
                     <button class="v-status v-status_${key} hidden cu-btn sx absolute bg-red position-left-half postion-center-x position-bottom-sm">已拒绝</button>
                 </div>`
    })
    $('#videos').prepend(html)
    $("#videos").trigger("create")
  } else {
    Object.keys(allMember).forEach((key) => {
      const url = baseconfig.avatarUrl +  '/' + key + '.jpg'
      const avatar = baseconfig.avatarUrl  + '/' + key + '.jpg'
      if (key == getQueryVariable('id')) {
        me = `<div class="v-item">
                     <div class="v-thumb v-thumb_${key} v-thumb-me">
                     <div class="v-thumb-bg" style="background:rgba(255,255,255,255.1) url(${url}) no-repeat center center;background-size: cover">  </div>
                        <img src="${avatar}" alt="" class="hidden">
                        <span class="hidden">${allMember[key]}</span>
                        <span class="my-sign text-brown cuIcon-favorfill"></span>
                        <video x5-playsinline playsinline webkit-playsinline preload id="my_video_${key}" autoplay poster="${url}" muted></video>
                      </div>
                      <div class="volume volume_${key}"></div>
                      <div class="v-close bg-white v-close_${key}">
                      <span class="text-red cuIcon-videofill"></span>
                     </div>
                 </div>`
      } else {
        html += `<div class="v-item">
                      <div class="v-thumb v-thumb_${key}">
                        <div class="v-thumb-bg" style="background:rgba(255,255,255,255.1) url(${url}) no-repeat center center;background-size: cover">  </div>
                        <img src="${avatar}" alt="">
                        <span>${allMember[key]}</span>
                        <video x5-playsinline playsinline webkit-playsinline preload id="my_video_${key}" autoplay poster="${url}"></video>
                       </div>
                      <div class="v-modal v-modal_${key}">
                        <span class="text-gray cuIcon-phone text-xxl hidden" data-key="${key}"></span>
                      </div>
                      <div class="volume volume_${key}"></div>
                      <div class="loader-71 loader_${key}"></div>
                      <span class="v-voice text-gray cuIcon-voicefill v-voice_${key}"></span>
                      <span class="v-record text-gray cuIcon-recordfill v-record_${key}"></span>
                      <button class="v-status v-status_${key} hidden  cu-btn sx absolute bg-red position-left-half postion-center-x position-bottom-sm">已拒绝</button>
                  </div>`
      }
    })
    html = html + me
    $('#videos').html(html)
    $("#videos").trigger("create")
  }
  if (Object.keys(allMember).length > 4) {
    $('.v-thumb img').css({
      'width': '40px',
      'height': '40px'
    })
  } else {
    $('.v-thumb img').css({
      'width': '80px',
      'height': '80px'
    })
  }
  $(`.v-item video`).off('click')
  $(`.v-item video`).on('click', function() {
    if (!callFlag) {
      return
    }
    if ($(this).hasClass('v-video_screen')) {
      $(this).closest('.v-item').removeClass('v-item_screen')
      $(this).closest('.v-item').children('.v-thumb').removeClass('v-thumb_screen')
      $(this).removeClass('v-video_screen')
    } else {
      $(this).closest('.v-item').addClass('v-item_screen')
      $(this).closest('.v-item').children('.v-thumb').addClass('v-thumb_screen')
      $(this).addClass('v-video_screen')
    }

  })
  $('.v-modal .cuIcon-phone').off('click')
  $('.v-modal .cuIcon-phone').on('click', function() {
    const key = $(this).attr('data-key')
    $(this).addClass('hidden')
    $('.v-status_' + key).addClass('hidden')
    $('.loader_' + key).removeClass('hidden')
    postMsg({
      groupRecall: 'groupRecall',
      message: allMember,
      uid: key
    }, '*');
  })
  $('.v-close').off('click')
  $('.v-close').on('click', function() {
    const b = $(this).hasClass('close')
    if (!b) {
      $(this).addClass('close line-white')
      $(this).removeClass('bg-white')
      localStream.getTracks().forEach(track => {
        if (track.kind === 'video') {
          track.enabled = false
        }
      });
      $('#my_video_' + getQueryVariable('id')).addClass('hidden')
      $(`.v-thumb_${getQueryVariable('id')} img`).removeClass('hidden')
      $(`.v-thumb_${getQueryVariable('id')} span`).removeClass('hidden')
    } else {
      localStream.getTracks().forEach(track => {
        if (track.kind === 'video') {
          track.enabled = true
        }
      });
      $(this).addClass('bg-white')
      $(this).removeClass('close line-white')
      $('#my_video_' + getQueryVariable('id')).removeClass('hidden')
      $(`.v-thumb_${getQueryVariable('id')} img`).addClass('hidden')
      $(`.v-thumb_${getQueryVariable('id')} span`).addClass('hidden')
    }
    postMsg({
      cameraSwitch: 'cameraSwitch',
      value: b
    }, '*')
  })
}
let addGroup = {}

function updateAddInfo(type) {
  if (type === 'voice') {
    updateGroupsInfo(addGroup)
  } else {
    updateGroupsInfoVideo(addGroup)
  }
}

function acceptVoice() {
  acceptCall = true
  postMsg({
    acceptVoice: 'acceptVoice',
  }, '*')
}

function acceptVideo() {
  acceptCall = true
  postMsg({
    acceptVideo: 'acceptVideo',
  }, '*');
}

let horn = true // 静音 false 扬声器true
function speakBtn() {
  speakBtnFunc((platform) => {
    const speakBtnText = document.getElementById('speakBtnText')
    if (horn) { //扬声器 => 静音
      console.log('静音')
      horn = !horn
      removeAllClass('speakBtnIn', 'bg-white')
      addAllClass('speakBtnIn', 'line-white')
      speakBtnText.innerHTML = '静音'
      addAllClass('speakBtnIn', 'close')
    } else { //静音 => 扬声器
      horn = !horn
      removeAllClass('speakBtnIn', 'line-white')
      addAllClass('speakBtnIn', 'bg-white')
      removeAllClass('speakBtnIn', 'close')
      if (platform == 'h5') speakBtnText.innerHTML = '听筒'
      if (platform == 'app') speakBtnText.innerHTML = '扬声器'
    }
  })
}

function speakBtnFunc(callBack) { //打开关闭扬声器 h5端就是静音 ROUTE_EARPIECE 听筒 ROUTE_SPEAKER 扬声器
  let allMember = JSON.parse(decodeURIComponent(getQueryVariable('group')))
  allMember = {
    ...allMember,
    ...addGroup
  }
  // console.log(allMember)
  Object.keys(allMember).forEach(key => {
    // console.log(key) 
    if (key == getQueryVariable('id')) return
    if (horn) { //扬声器 => 静音
      console.log('静音')
      document.getElementById('my_video_' + key).muted = true
    } else { //静音 => 扬声器
      document.getElementById('my_video_' + key).muted = false
    }
  })

  callBack && callBack(getQueryVariable('platform'))
}

let headset = true //麦克风 打开true 关闭false,
function voiceBtn() {
  voiceBtnFunc((platform, headset) => {
    if (headset) { //打开 => 关闭
      removeAllClass('voiceBtnIn', 'bg-white')
      addAllClass('voiceBtnIn', 'line-white')
      addAllClass('voiceBtnIn', 'close')
      $(`.v-voice_${getQueryVariable('id')}`).removeClass('text-green')
      $(`.v-voice_${getQueryVariable('id')}`).addClass('text-gray')
    } else {
      removeAllClass('voiceBtnIn', 'line-white')
      removeAllClass('voiceBtnIn', 'close')
      addAllClass('voiceBtnIn', 'bg-white')
      $(`.v-voice_${getQueryVariable('id')}`).removeClass('text-gray')
      $(`.v-voice_${getQueryVariable('id')}`).addClass('text-green')
    }
    postMsg({
      voiceSwitch: 'voiceSwitch',
      value: !headset
    }, '*')
  })
}

function voiceBtnFunc(callBack) { //打开麦克风和关闭麦克风
  if (headset) { //打开 => 关闭
    headset = !headset
    localStream.getTracks().forEach(track => track.enabled = false);
  } else {
    headset = !headset
    localStream.getTracks().forEach(track => track.enabled = true);
  }
  callBack && callBack(getQueryVariable('platform'), !headset)
}

function videoBtn() {
  videoBtnFunc((platform, headset) => {
    if (headset) {
      removeAllClass('voiceBtnIn', 'bg-white')
      addAllClass('voiceBtnIn', 'line-white')
      addAllClass('voiceBtnIn', 'close')
    } else {
      removeAllClass('voiceBtnIn', 'line-white')
      removeAllClass('voiceBtnIn', 'close')
      addAllClass('voiceBtnIn', 'bg-white')
    }
    postMsg({
      voiceSwitch: 'voiceSwitch',
      value: !headset
    }, '*')
  })
}

function videoBtnFunc(callBack) {
  if (headset) { //打开 => 关闭
    headset = !headset
    localStream.getTracks().forEach(track => {
      if (track.kind === 'audio') {
        track.enabled = false
      }
    });
  } else {
    headset = !headset
    localStream.getTracks().forEach(track => {
      if (track.kind === 'audio') {
        track.enabled = true
      }
    });
  }
  callBack && callBack(getQueryVariable('platform'), !headset)
}

function exchangeVideo() {
  uniRtc.exchangeVideo()
}

function changeVideo() {
  uniRtc.changeVideo((platform, horn) => {
    if (horn) {
      removeAllClass('speakBtnIn', 'bg-white')
      addAllClass('speakBtnIn', 'line-white')
    } else {
      removeAllClass('speakBtnIn', 'line-white')
      addAllClass('speakBtnIn', 'bg-white')
    }
  })
}

function handleClose() {
  $('.tk-modal').removeClass('show')
}

function handleOpen() {
  if (callFlag) {
    $('.tk-modal').addClass('show')
  } else {
    cancelBtn()
  }
}

function handleQuit() { // 邀请方退出房间
  let group = JSON.parse(decodeURIComponent(getQueryVariable('group')))
  const isExit = Object.keys(group).every(item => !window.pc[item])
  if (isExit) {
    cancelBtn(1)
    return
  }
  quitRtc(() => {
    localStream.getTracks().forEach(track => track.stop());
    Object.keys(group).forEach(key => {
      window.pc[key] && window.pc[key].close()
      delete window.pc[key]
    })
  }, 0)
}

function finishBtn() {
  let group = JSON.parse(decodeURIComponent(getQueryVariable('group')))
  const isExit = Object.keys(group).every(item => !window.pc[item])
  if (isExit) {
    cancelBtn(1)
    return
  }
  hangupAction(() => {
    localStream.getTracks().forEach(track => track.stop());
    Object.keys(group).forEach(key => {
      window.pc[key] && window.pc[key].close();
      delete window.pc[key]
    })
  }, 0)
}

function cancelBtn(type) { // 邀请方取消会议
  let group = JSON.parse(decodeURIComponent(getQueryVariable('group')))
  if (type === 1) {
    noBody(() => {
      Object.keys(group).forEach(key => {
        window.pc[key] && window.pc[key].close()
        delete window.pc[key]
        callFlag = false
      })
    })
    return
  }
  cancelCall(() => {
    window.pc = {}
    callFlag = false
  }, 0)
}

function cancelBtnd() { // 被邀请方退出/或者拒绝
  let group = JSON.parse(decodeURIComponent(getQueryVariable('group')))
  if (callFlag) { // 退出房间
    const isExit = Object.keys(group).every(item => !window.pc[item])
    if (isExit) {
      cancelBtn(1)
      return
    }
    quitRtc(() => {
      localStream.getTracks().forEach(track => track.stop());
      Object.keys(group).forEach(key => {
        window.pc[key] && window.pc[key].close()
        delete window.pc[key]
        callFlag = false
      })
    }, 0)

  } else { // 拒绝接听
    rejectCall(() => {
      localStream.getTracks().forEach(track => track.stop());
      Object.keys(group).forEach(key => {
        window.pc[key] && window.pc[key].close()
        delete window.pc[key]
        callFlag = false
      })
    }, 0)
  }
}
let disable_voice = false //　true 禁言 false 取消禁言
function disableVoice() {
  if (!disable_voice) { //禁言
    disable_voice = !disable_voice
    $('.allVoice').addClass('close')
  } else { // 解除禁言
    disable_voice = !disable_voice
    $('.allVoice').removeClass('close')
  }
  postMsg({
    voiceDisable: 'voiceDisable',
    value: disable_voice
  }, '*')
}

function createOffer(message) {
  window.pc[message.sender].createOffer(offerParams).then((offer) => {
    window.pc[message.sender].setLocalDescription(offer);
    postMsg({
      offer: 'offer',
      sdp: offer.sdp,
      message: message
    }, '*');
  });
}

function createAnswer(message) {
  window.pc[message.sender].createAnswer(offerParams).then((answer) => {
    window.pc[message.sender].setLocalDescription(answer);
    postMsg({
      answer: 'answer',
      sdp: answer.sdp,
      message: message
    }, '*');
  });
}

function setRemoteDescriptionAnswer(sdp, message) { // 添加本地answer
  window.pc[message.sender].setRemoteDescription(new RTCSessionDescription({
    type: 'answer',
    sdp: sdp
  }));
}

function setRemoteDescriptionOffer(sdp, message) { //添加本地offer
  window.pc[message.sender].setRemoteDescription(new RTCSessionDescription({
    type: 'offer',
    sdp: sdp
  }));
}

function addIceCandidate(iceCandidate, message) { // 同步ice
  console.log(window.pc)
  console.log(window.pc[message.sender])

  console.log(message.sender)
  console.log(window.pc[message.sender])
  window.pc[message.sender].addIceCandidate(new RTCIceCandidate(iceCandidate));
}

function busyCall(callBack, idfer) { //对方忙线
  postMsg({
    busyCall: 'busyCall',
    idfer: idfer
  }, '*');
  callBack && callBack()
}

function rejectCall(callBack, idfer) { //拒绝电话
  postMsg({
    rejectCall: 'rejectCall',
    idfer: idfer
  }, '*');
  callBack && callBack()
}

function timeOut(callBack, idfer) { // 超时
  if (idfer === 1) {
    postMsg({
      timeOut: 'timeOut',
      idfer: idfer
    }, '*');
  }
  callBack && callBack()
}

function hangupAction(callBack, idfer) { //挂断电话
  // if(idfer == 1) timeString = ''
  // console.log('挂断电话挂断电话挂断电话挂断电话挂断电话挂断电话')
  // console.log(idfer, timeString)
  postMsg({
    hangup: 'hangup',
    idfer: idfer,
    time: timeString
  }, '*');
  callBack && callBack()
}

function quitRtc(callBack, idfer) { //退出房间电话
  postMsg({
    quitRtc: 'quitRtc',
    idfer: idfer,
    time: timeString
  }, '*');
  callBack && callBack()
}

function cancelCall(callBack, idfer) { //取消呼叫电话
  if (idfer == 1) timeString = ''
  console.log('取消呼叫电话取消呼叫电话取消呼叫电话取消呼叫电话取消呼叫电话')
  console.log(idfer)
  postMsg({
    cancelCall: 'cancelCall',
    idfer: idfer
  }, '*');
  callBack && callBack()
}

function noBody(callBack) { //都已经退出房间
  postMsg({
    noBody: 'noBody',
    time: timeString
  }, '*');
  callBack && callBack()
}

function postMsg(data) { // 页面通讯
  if (getQueryVariable('platform') === 'app') {
    uni.postMessage({
      data: data
    })
  } else {
    window.parent.postMessage(data)
  }
}

function handleInvite(type) {
  const event = window.event || arguments.callee.caller.arguments[0]
  event.stopPropagation()
  allMember = {
    ...allMember,
    ...addGroup
  }
  if (Object.keys(allMember).length === 9) {
    return
  }
  // console.log(getQueryVariable('gid'))
  if (getQueryVariable('gid') == 'undefined') {
    uni.navigateTo({
      url: "/pages/rtc/inviteBook?type=" + type + '&group=' + JSON.stringify(
        allMember) + '&add=add'
    })
    return
  } else {
    $('.popupoverInvite').addClass('active')
  }
  // uni.navigateTo({
  //   url: "/pages/rtc/invite?type=" + type + "&id=" + getQueryVariable('gid') + '&group=' + JSON.stringify(
  //     allMember) + '&add=add'
  // })
}

function invite(type) {
  if (type == 1) {
    uni.navigateTo({
      url: "/pages/rtc/invite?type=" + type + "&id=" + getQueryVariable('gid') + '&group=' + JSON.stringify(
        allMember) + '&add=add'
    })
  } else {
    uni.navigateTo({
      url: "/pages/rtc/inviteBook?type=" + type + '&group=' + JSON.stringify(
        allMember) + '&add=add'
    })
  }
}
$('body').on('click', function() {
  $('.popupoverInvite').removeClass('active')
})

function volumeWave(stream, id) {
  let audioContext = new(window.AudioContext || window.webkitAudioContext)()
  let mediaStreamSource = null
  let scriptProcessor = null
  mediaStreamSource = audioContext.createMediaStreamSource(stream)
  scriptProcessor = audioContext.createScriptProcessor(4096, 1, 1)
  //设置音量节点
  scriptProcessor.onaudioprocess = function(e) {
    // 获得缓冲区的输入音频，转换为包含了PCM通道数据的32位浮点数组
    let buffer = e.inputBuffer.getChannelData(0)
    // 获取缓冲区中最大的音量值
    let maxVal = Math.max.apply(Math, buffer);
    // 显示音量值
    // setAudiotNum(Math.ceil(maxVal * 100))
    // console.log(Math.floor(maxVal * 100))
    // console.log($('.volume_' + id + '::after'))
    // $('head').append(`<style>.volume_${id}::after{ width:${Math.floor(maxVal * 100)} }</style>`);
    if (Math.floor(maxVal * 100) > 1) {
      $('.v-voice_' + id).addClass('volume_ripple')
    } else {
      $('.v-voice_' + id).on('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend',
        () => {
          //css3动画播放完了 再移除
          $('.v-voice_' + id).removeClass('volume_ripple')
        });
    }
    // console.log(maxVal)
    if (maxVal > 0.5) {
      // mediaStreamSource.disconnect(scriptProcessor);
    } else {
      // mediaStreamSource.connect(scriptProcessor);
    }
  };
  mediaStreamSource.connect(scriptProcessor)
  scriptProcessor.connect(audioContext.destination)
}